<?php


namespace app\api\controller\v21;


use app\api\controller\v2\Auth;
use app\common\cachemodel\AppQq;
use app\common\cachemodel\AppWeibo;
use app\common\cachemodel\Recode;
use app\common\cachemodel\Wechat;
use app\common\cachemodel\ZlAppleidUser;
use app\common\cachemodel\ZlUserLoginRecord;
use app\common\lib\Util;
use app\common\model\Rectification as RectificationModel;

class User extends Auth
{
    /**
     * 获取用户信息
     */
    public function getInfo()
    {
        try
        {
            $data = [];
            if ($this->user['rid'])
            {   // 有档案
                $recode = (new Recode())->getRecodeLists($this->user['id'], 1);
                $data['name'] = $recode['name'];
                $data['sex'] = (int)$recode['type'] === 1 ? 1 : 2;
                $data['year'] = (int)$recode['year'];
                $data['month'] = (int)sprintf('%02u', $recode['month']);
                $data['day'] = (int)sprintf('%02u', $recode['day']);
                $data['hour'] = (int)sprintf('%02u', $recode['hour']);
                $data['minute'] = (int)sprintf('%02u', $recode['minute']);
                $data['timezone'] = (int)$recode['timezone'];
                $data['birth_country'] = $recode['birth_country'];
                $data['birth_province'] = $recode['birth_province'];
                $data['birth_city'] = $recode['birth_city'];
                $data['live_country'] = $recode['live_country'];
                $data['live_province'] = $recode['live_province'];
                $data['live_city'] = $recode['live_city'];
                $data['long_deg'] = (int)$recode['long_deg'];
                $data['long_min'] = (int)$recode['long_min'];
                $data['ew'] = (int)$recode['ew'];
                $data['lat_deg'] = (int)$recode['lat_deg'];
                $data['lat_min'] = (int)$recode['lat_min'];
                $data['ns'] = (int)$recode['ns'];
                $data['avatar'] = $recode['avatar'];
                $data['tel'] = '';
            } else
            {
                $data['name'] = $this->user['nickname'];
                $data['avatar'] = $this->user['avatar'];
            }


            //判断用户是否绑定微信
            $wechat_info = (new Wechat())->getWechatInfo($this->user['id'], 2);
            if ($wechat_info)
            {
                $data['nickname'] = $wechat_info['nickname'];
            } else
            {
                $data['nickname'] = '';
            }
            //判断用户是否绑定了qq
            $qq_info = (new AppQq())->getUserQqInfoFromCache($this->user['id'], 2);
            if ($qq_info)
            {
                $data['qq_name'] = $qq_info['nickname'];
            } else
            {
                $data['qq_name'] = '';
            }
            //判断用户是否绑定了微博
            $wb_info = (new AppWeibo())->getUserWbInfoFromCache($this->user['id'], 2);
            if ($wb_info)
            {
                $data['wb_name'] = $wb_info['nickname'];
            } else
            {
                $data['wb_name'] = '';
            }

            if ($this->headers['app-type'] === 'ios')
            {
                $data['is_bind_apple'] = (new ZlAppleidUser())->getAppleId($this->user['id']) ? 1 : 0; // 是否绑定苹果ID
            }

            $field = 'id,status';
            //判断用户是否矫正中
            $where = ['uid' => $this->user['id'], 'status' => ['eq', 1]];
            $rectification = (new RectificationModel())
                ->field($field)
                ->where($where)
                ->count('id');

            if ($rectification > 0)
            {
                $data['is_rectification'] = 1;
            } else
            {
                $data['is_rectification'] = 0;
            }

        }
        catch (\Exception $e)
        {
            return show(config('code.denied'), '用户信息获取失败,请重新登录');
        }

        if ($this->user['tel'])
        {
            $str = substring($this->user['tel'], '-');
            $tel = $str['after'];
            $data['area_code'] = (int)$str['before'] ?: 86;
            $data['tel'] = Util::hidtel($tel, $data['area_code']);

            $data['is_temporary_tel'] = 0;    // 是否绑定临时手机号 0不是 1是 缓存字段不存在时 默认就数据 不是临时手机号
        } else
        {
            if ($this->user['temporary_tel'])
            {   // 临时手机号
                $str = substring($this->user['temporary_tel'], '-');
                $tel = $str['after'];
                $data['area_code'] = (int)$str['before'] ?: 86;
                $data['tel'] = Util::hidtel($tel, $data['area_code']);
                $data['is_temporary_tel'] = 1; // 是否绑定临时手机号 0不是 1是 当前还未绑定手机号
            } else
            {
                $data['tel'] = '';
                $data['is_temporary_tel'] = 0; // 是否绑定临时手机号 0不是 1是 当前还未绑定手机号
            }
        }

        return show(200, '成功', $data);
    }

    /**
     * 获取登陆记录
     */
    public function getLoginRecord()
    {
        $recordDatas = (new ZlUserLoginRecord())->getRecordList($this->user['id']);

        $isLoginRecord = (int)($this->user['is_login_record'] ?? 1);  // 是否记录设备登陆历史 1=>记录，2=>不记录

        $data = [
            'status' => $isLoginRecord,
            'login_record_list' => $recordDatas
        ];

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 设置记录登陆设备日志状态
     */
    public function setLoginRecordStatus()
    {
        $status = input('status/d', 1);

        if (!in_array($status, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，操作失败。');
        }

        (new \app\common\model\User())->updateUserinfo(['id' => $this->user['id']], ['is_login_record' => $status]);

        return show(config('code.success'), '操作成功');
    }

    /**
     *  删除登陆设备记录
     */
    public function loginRecordDel()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常，删除失败。');
        }

        $recordInfo = (new ZlUserLoginRecord())->getInfoById($id, ['uid']);

        if (!$recordInfo || (int)$recordInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '记录不存在，删除失败。');
        }


        $res = (new ZlUserLoginRecord())->recordDel($this->user['id'], $id);

        if ($res)
        {
            return show(config('code.success'), '删除成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }
}
